// 43.字符串相乘
// https://leetcode.cn/problems/multiply-strings/description/

/**
 * 示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"

示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
 

提示：

1 <= num1.length, num2.length <= 200
num1 和 num2 只能由数字组成。
num1 和 num2 都不包含任何前导零，除了数字0本身。
 */

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var multiply = function (num1, num2) {
    if (num1 === '0' || num2 === '0') return '0';

    let res = '0';

    const arrNum2 = [...num2].map((e) => parseInt(e));
    for (let i = arrNum2.length - 1; i >= 0; i--) {
        const curNum2 = arrNum2[i];
        let curRes = multiplySingle(num1, curNum2);
        // 补零
        for (let j = 0; j < arrNum2.length - i - 1; j++) {
            curRes += '0';
        }

        res = strPlus(res, curRes);

        // console.log(`${num1} * ${curNum2} = ${curRes}, res is ${res}`);
    }
    console.log(`${num1} * ${num2} = ${res}`);
    return res;
};

function strPlus(num1, num2) {
    let ret = '';
    let add = 0;

    const arr1 = [...num1].map((e) => parseInt(e)).reverse();
    const arr2 = [...num2].map((e) => parseInt(e)).reverse();
    const maxLen = Math.max(arr1.length, arr2.length);

    for (let i = 0; i < maxLen; i++) {
        const num1 = arr1.length - 1 >= i ? arr1[i] : 0;
        const num2 = arr2.length - 1 >= i ? arr2[i] : 0;

        let curRes = num1 + num2 + add;

        add = curRes >= 10 ? 1 : 0;
        ret += curRes >= 10 ? curRes - 10 : curRes;
    }

    if (add == 1) {
        ret += 1;
    }

    return ret.split('').reverse().join('');
}

function multiplySingle(num1, num2) {
    if (num1 == '0' || num2 == '0') return '0';

    let ret = '';
    let add = 0;
    const arrNum1 = [...num1].map((e) => parseInt(e));

    for (let i = arrNum1.length - 1; i >= 0; i--) {
        const res = arrNum1[i] * num2 + add;

        add = Math.floor(res / 10);
        ret = (res % 10) + ret;
    }

    if (add > 0) {
        ret = add + ret;
    }

    return ret;
}

multiply('2', '3'); // 6
multiply('2', '9'); // 18
multiply('123', '456'); // 56088
multiply('123', '0'); // 0
multiply('123456789', '987654321'); // 121932631112635269
